from django.db import models
from django.utils import timezone
import uuid
from .wechat_user import WechatUser
from django.contrib.auth.models import User

class VipActivationCode(models.Model):
    """VIP激活码模型"""
    code = models.CharField(max_length=32, unique=True, verbose_name='激活码')
    vip_type = models.CharField(max_length=20, choices=[
        ('month', '月度会员'),
        ('year', '年度会员'),
        ('lifetime', '永久会员')
    ], verbose_name='会员类型')
    is_used = models.BooleanField(default=False, verbose_name='是否已使用')
    used_by = models.ForeignKey(WechatUser, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='使用者')
    used_at = models.DateTimeField(null=True, blank=True, verbose_name='使用时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    expired_at = models.DateTimeField(null=True, blank=True, verbose_name='过期时间')

    class Meta:
        verbose_name = 'VIP激活码'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.code} - {self.get_vip_type_display()}"

    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            'id': self.id,
            'code': self.code,
            'vip_type': self.vip_type,
            'vip_type_display': self.get_vip_type_display(),
            'is_used': self.is_used,
            'used_by': {
                'id': self.used_by.id,
                'nickname': self.used_by.nickname
            } if self.used_by else None,
            'used_at': self.used_at.strftime('%Y-%m-%d %H:%M:%S') if self.used_at else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'expired_at': self.expired_at.strftime('%Y-%m-%d %H:%M:%S') if self.expired_at else None
        }

    @classmethod
    def generate_code(cls, vip_type):
        """生成新的激活码"""
        code = str(uuid.uuid4()).replace('-', '')[:16].upper()
        return cls.objects.create(
            code=code,
            vip_type=vip_type
        )

class VipMember(models.Model):
    """VIP会员模型"""
    user = models.OneToOneField(WechatUser, on_delete=models.CASCADE, verbose_name='用户')
    vip_type = models.CharField(max_length=20, choices=[
        ('month', '月度会员'),
        ('year', '年度会员'),
        ('lifetime', '永久会员')
    ], verbose_name='会员类型')
    start_time = models.DateTimeField(auto_now_add=True, verbose_name='开始时间')
    end_time = models.DateTimeField(null=True, blank=True, verbose_name='结束时间')
    is_active = models.BooleanField(default=True, verbose_name='是否有效')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = 'VIP会员'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.nickname} - {self.get_vip_type_display()}"

    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            'id': self.id,
            'user': {
                'id': self.user.id,
                'nickname': self.user.nickname,
                'avatar': self.user.avatar
            },
            'vip_type': self.vip_type,
            'vip_type_display': self.get_vip_type_display(),
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'end_time': self.end_time.strftime('%Y-%m-%d %H:%M:%S') if self.end_time else None,
            'is_active': self.is_active,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }

    def check_vip_status(self):
        """检查VIP状态"""
        if self.vip_type == 'lifetime':
            return True
        if not self.end_time:
            return False
        return timezone.now() <= self.end_time

    def activate(self, vip_type, duration_days=None):
        """激活或续期VIP"""
        self.vip_type = vip_type
        if vip_type == 'lifetime':
            self.end_time = None
        else:
            if duration_days is None:
                duration_days = 30 if vip_type == 'month' else 365
            if self.end_time and self.end_time > timezone.now():
                # 如果当前会员未过期，在现有结束时间基础上增加时长
                self.end_time = self.end_time + timezone.timedelta(days=duration_days)
            else:
                # 如果当前会员已过期或不存在，从当前时间开始计算
                self.end_time = timezone.now() + timezone.timedelta(days=duration_days)
        self.is_active = True
        self.save()

class VipPackage(models.Model):
    """VIP套餐模型"""
    name = models.CharField(max_length=50, verbose_name='套餐名称')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    duration = models.IntegerField(verbose_name='时长(天)')
    description = models.TextField(verbose_name='描述')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'vip_package'
        verbose_name = 'VIP套餐'
        verbose_name_plural = verbose_name
        ordering = ['price']

    def __str__(self):
        return self.name

    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'price': float(self.price),
            'duration': self.duration,
            'description': self.description,
            'is_active': self.is_active,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }

class VipOrder(models.Model):
    """VIP订单模型"""
    PAYMENT_STATUS_CHOICES = (
        ('pending', '待支付'),
        ('paid', '已支付'),
        ('cancelled', '已取消'),
    )
    
    PAYMENT_METHOD_CHOICES = (
        ('alipay', '支付宝'),
        ('wechat', '微信支付'),
    )
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    package = models.ForeignKey(VipPackage, on_delete=models.CASCADE, verbose_name='套餐')
    order_no = models.CharField(max_length=50, unique=True, verbose_name='订单号')
    amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='金额')
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD_CHOICES, verbose_name='支付方式')
    payment_status = models.CharField(max_length=20, choices=PAYMENT_STATUS_CHOICES, default='pending', verbose_name='支付状态')
    paid_at = models.DateTimeField(null=True, blank=True, verbose_name='支付时间')
    expire_at = models.DateTimeField(null=True, blank=True, verbose_name='过期时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'vip_order'
        verbose_name = 'VIP订单'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.username} - {self.package.name}"

    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            'id': self.id,
            'user': {
                'id': self.user.id,
                'username': self.user.username
            },
            'package': self.package.to_dict(),
            'order_no': self.order_no,
            'amount': float(self.amount),
            'payment_method': self.payment_method,
            'payment_method_display': self.get_payment_method_display(),
            'payment_status': self.payment_status,
            'payment_status_display': self.get_payment_status_display(),
            'paid_at': self.paid_at.strftime('%Y-%m-%d %H:%M:%S') if self.paid_at else None,
            'expire_at': self.expire_at.strftime('%Y-%m-%d %H:%M:%S') if self.expire_at else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        } 